import React, { useState, useEffect, useRef, useCallback } from 'react';
import Header from "../../components/Header/Header.tsx";
import BookCard, { BookInfo } from "../../components/BookCard/BookCard";
import { Input, Dropdown, Empty, Spin } from 'antd';
import { BookOutlined, SearchOutlined, EllipsisOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { MenuProps } from 'antd';
import { listBookCategories } from "../../api/bookCategoryController";
import { listBookByPage } from "../../api/bookController";

const Library: React.FC = () => {
  const [activeTab, setActiveTab] = useState('all');
  const [searchValue, setSearchValue] = useState('');
  const [books, setBooks] = useState<any[]>([]);
  const [categories, setCategories] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 8,
    total: 0
  });
  
  const loadingRef = useRef<HTMLDivElement>(null);
  const navigate = useNavigate();
  
  // 获取分类数据
  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const res = await listBookCategories();
        if (res.code === 200) {
          setCategories(res.data);
        }
      } catch (error) {
        console.error('获取分类失败:', error);
      }
    };
    fetchCategories();
  }, []);

  // 获取图书数据
  const fetchBooks = useCallback(async (isLoadMore = false) => {
    setLoading(true);
    try {
      const params = {
        current: pagination.current,
        pageSize: pagination.pageSize,
        bookname: searchValue,
        bookauthor: '',
        categorycode: [activeTab]
      };

      const res = await listBookByPage(params);
      if (res.code === 200) {
        const newBooks = res.data.records;
        setBooks(prev => isLoadMore ? [...prev, ...newBooks] : newBooks);
        setPagination(prev => ({
          ...prev,
          total: parseInt(res.data.total)
        }));
        setHasMore(res.data.records.length === pagination.pageSize);
      }
    } catch (error) {
      console.error('获取图书列表失败:', error);
    } finally {
      setLoading(false);
    }
  }, [pagination.current, pagination.pageSize, searchValue, activeTab]);

  // 添加 Intersection Observer
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && hasMore && !loading) {
          setPagination(prev => ({ ...prev, current: prev.current + 1 }));
        }
      },
      { threshold: 0.1 }
    );

    if (loadingRef.current) {
      observer.observe(loadingRef.current);
    }

    return () => observer.disconnect();
  }, [hasMore, loading]);

  // 修改初始加载效果
  useEffect(() => {
    if (pagination.current === 1) {
      fetchBooks(false);
    } else {
      fetchBooks(true);
    }
  }, [fetchBooks]);

  // 修改搜索和分类切换的处理方法
  const handleSearch = (value: string) => {
    setSearchValue(value);
    setBooks([]);
    setPagination(prev => ({ ...prev, current: 1 }));
    setHasMore(true);
  };

  const handleTabChange = (categoryCode: string) => {
    setActiveTab(categoryCode);
    setBooks([]);
    setPagination(prev => ({ ...prev, current: 1 }));
    setHasMore(true);
  };

  // 下拉菜单项
  const dropdownItems: MenuProps['items'] = categories.slice(5).map(category => ({
    key: category.categorycode,
    label: category.categorynamezh,
    onClick: () => handleTabChange(category.categorycode),
  }));

  return (
    <div className="h-screen flex flex-col overflow-auto">
      <Header />
      <div className="flex-1 w-full max-w-[1400px] mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div className="flex flex-col space-y-6">
          {/* Tab和搜索区域 */}
          <div className="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-4">
            {/* Tab导航区域 */}
            <div className="w-full lg:flex-1 overflow-hidden">
              <div className="flex items-center space-x-4 overflow-x-auto scrollbar-thin scrollbar-thumb-gray-300 
                            scrollbar-track-gray-100 hover:scrollbar-thumb-gray-400 pb-2">
                {/* 大屏幕显示所有标签 */}
                <div className="hidden lg:flex items-center space-x-4 flex-nowrap">
                  {categories.map(category => (
                    <button
                      key={category.categorycode}
                      className={`px-6 py-2 rounded-full text-base transition-colors duration-300 whitespace-nowrap flex-shrink-0 ${
                        activeTab === category.categorycode
                          ? 'bg-blue-500 text-white'
                          : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                      }`}
                      onClick={() => handleTabChange(category.categorycode)}
                    >
                      {category.categorynamezh}
                    </button>
                  ))}
                </div>

                {/* 小屏幕显示部分标签和更多按钮 */}
                <div className="flex lg:hidden items-center space-x-4 flex-nowrap">
                  {categories.slice(0, 5).map(category => (
                    <button
                      key={category.categorycode}
                      className={`px-6 py-2 rounded-full text-base transition-colors duration-300 whitespace-nowrap flex-shrink-0 ${
                        activeTab === category.categorycode
                          ? 'bg-blue-500 text-white'
                          : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                      }`}
                      onClick={() => handleTabChange(category.categorycode)}
                    >
                      {category.categorynamezh}
                    </button>
                  ))}
                  
                  <Dropdown
                    menu={{ items: dropdownItems }}
                    trigger={['click']}
                    placement="bottomRight"
                    overlayClassName="min-w-[120px]"
                  >
                    <button className="px-6 py-2 rounded-full text-base bg-gray-100 text-gray-600 hover:bg-gray-200 flex-shrink-0">
                      <EllipsisOutlined />
                    </button>
                  </Dropdown>
                </div>
              </div>
            </div>

            {/* 搜索框 */}
            <div className="w-full lg:w-[300px] flex justify-center lg:justify-end">
              <div className="w-full max-w-md lg:max-w-none">
                <Input
                  size="large"
                  placeholder="搜索图书"
                  prefix={<SearchOutlined />}
                  onChange={e => handleSearch(e.target.value)}
                  className="rounded-full"
                />
              </div>
            </div>
          </div>

          {/* 图书列表 */}
          <div className="w-full">
            {books.length > 0 ? (
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 sm:gap-6">
                {books.map((book) => (
                  <div key={book.id}>
                    <BookCard
                      book={{
                        id: book.id,
                        name: book.bookname,
                        title: `${book.bookauthor}著 - ${book.bookdesc}`,
                        image: book.imageurl,
                        publishTime: book.publishdate.split(' ')[0],
                        category: book.categorycode
                      }}
                      onViewDetail={() => navigate(`/book/${book.id}`)}
                    />
                  </div>
                ))}
              </div>
            ) : !loading && (
              <div className="flex justify-center items-center min-h-[400px]">
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description={
                    <span className="text-gray-500">
                      暂无相关图书
                    </span>
                  }
                />
              </div>
            )}
            
            {/* 添加加载更多提示器 */}
            <div ref={loadingRef} className="w-full py-4 flex justify-center">
              {loading && <Spin />}
              {!loading && !hasMore && books.length > 0 && (
                <span className="text-gray-500">没有更多数据了</span>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Library; 